package com.sy.simpleegg.upgrade

import com.sy.simpleegg.util.FileUtil
import java.io.File
import java.io.RandomAccessFile

class UpgradeUtil (
    private val versionName: String,
    private val savePath: String,
    private val blockTotal: Long
){

    private var basePath = ""
    init {
        basePath = if (savePath.endsWith("/")) "$savePath$versionName/" else "$savePath/$versionName/"
    }

    /**
     * 保存更新包数据
     * @param byteArray 数据内容
     * @param blockSort 序号
     */
    suspend fun saveBlock(byteArray: ByteArray, blockSort: Long): Boolean{
        var result = false
        val outPutFile = File(basePath + "block_${blockSort}.temp")
        var raf: RandomAccessFile? = null
        try {
            raf = RandomAccessFile(outPutFile, "rw")
            val dataLen = byteArray.size
            val b = ByteArray(1024)
            val count = if (dataLen%b.size == 0) dataLen/b.size else (dataLen/b.size) + 1

            for (i in 0 until count){
                val copyLen = if (i <= count - 2) b.size else dataLen%b.size
                System.arraycopy(byteArray, i*b.size, b, 0, copyLen)
                raf.write(b, 0, copyLen)
            }

            result = true
        }catch (e: Exception){
            e.printStackTrace()
        }finally {
            try {
                raf?.close()
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
        return result
    }

    suspend fun mergeBlocks(): String{
        return try {
            val outPutFile = basePath + "install.apk"
            val dirUpgrade = File(basePath)
            dirUpgrade.listFiles()?.run {
                sortWith { f1, f2 ->
                    f1.name.compareTo(f2.name)
                }
                val pathList: MutableList<String> = mutableListOf()
                forEach { file ->
                    pathList.add(file.absolutePath)
                }
                FileUtil.mergeFiles(outPutFile, pathList)
            }
            outPutFile
        }catch (e: Exception){
            e.printStackTrace()
            ""
        }
    }

    suspend fun install(){
        mergeBlocks()

    }
}